<template>
  <div class="dispatch-management">
    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.totalPlans }}</div>
                <div class="stats-label">总调度计划</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon active">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.activePlans }}</div>
                <div class="stats-label">执行中计划</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.pendingPlans }}</div>
                <div class="stats-label">待执行计划</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statsData.completedPlans }}</div>
                <div class="stats-label">已完成计划</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="计划名称">
          <el-input
            v-model="queryForm.planName"
            placeholder="请输入计划名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="调度类型">
          <el-select v-model="queryForm.dispatchType" placeholder="请选择调度类型" style="width: 150px" clearable>
            <el-option label="防洪调度" value="flood-control" />
            <el-option label="供水调度" value="water-supply" />
            <el-option label="发电调度" value="power-generation" />
            <el-option label="生态调度" value="ecological" />
            <el-option label="综合调度" value="comprehensive" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" style="width: 120px" clearable>
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="showAddDialog">新增调度计划</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="VideoPlay" :disabled="selectedRows.length === 0" @click="handleBatchExecute">批量执行</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Calendar" @click="showScheduleCalendar">调度日历</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Monitor" @click="showDispatchCenter">调度中心</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planName" label="计划名称" min-width="200">
          <template #default="{ row }">
            <div class="plan-name">
              <el-icon class="plan-icon">
                <component :is="getDispatchIcon(row.dispatchType)" />
              </el-icon>
              <span>{{ row.planName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="dispatchType" label="调度类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.dispatchType)" size="small">
              {{ getTypeText(row.dispatchType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="执行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scheduledTime" label="计划执行时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.scheduledTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualStartTime" label="实际开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.actualStartTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="执行进度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :status="row.progress === 100 ? 'success' : ''"
              :stroke-width="6"
            />
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="viewDetail(scope.row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="editPlan(scope.row)" :disabled="scope.row.status === 'executing'">编辑</el-button>
            <el-button link type="warning" icon="VideoPlay" @click="executePlan(scope.row)" :disabled="scope.row.status === 'executing' || scope.row.status === 'completed'">执行</el-button>
            <el-button link type="info" icon="VideoPause" @click="pausePlan(scope.row)" :disabled="scope.row.status !== 'executing'">暂停</el-button>
            <el-button link type="danger" icon="Delete" @click="deletePlan(scope.row)" :disabled="scope.row.status === 'executing'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination
          :total="pagination.total"
          v-model:page="pagination.currentPage"
          v-model:limit="pagination.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 调度计划表单对话框 -->
    <DispatchFormDialog
      v-model:visible="formDialogVisible"
      :form-data="currentFormData"
      :is-edit="isEditMode"
      @save="handleSave"
    />

    <!-- 调度计划详情对话框 -->
    <DispatchDetailDialog
      v-model:visible="detailDialogVisible"
      :dispatch-data="currentDetailData"
      @edit="editPlan"
      @execute="executePlan"
    />

    <!-- 调度执行对话框 -->
    <DispatchExecuteDialog
      v-model:visible="executeDialogVisible"
      :dispatch-data="currentExecuteData"
      @execution-complete="handleExecutionComplete"
    />

    <!-- 调度日历对话框 -->
    <ScheduleCalendarDialog
      v-model:visible="calendarDialogVisible"
      :schedule-data="scheduleData"
      @plan-selected="viewDetail"
    />

    <!-- 调度中心对话框 -->
    <DispatchCenterDialog
      v-model:visible="centerDialogVisible"
      :active-plans="activePlans"
      @plan-control="handlePlanControl"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar,
  VideoPlay,
  Clock,
  CircleCheck,
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
  Monitor,
  Umbrella,
  Lightning,
  Folder,
  Setting
} from '@element-plus/icons-vue'
import DispatchFormDialog from './components/DispatchFormDialog.vue'
import DispatchDetailDialog from './components/DispatchDetailDialog.vue'
import DispatchExecuteDialog from './components/DispatchExecuteDialog.vue'
import ScheduleCalendarDialog from './components/ScheduleCalendarDialog.vue'
import DispatchCenterDialog from './components/DispatchCenterDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 统计数据
const statsData = reactive({
  totalPlans: 156,
  activePlans: 8,
  pendingPlans: 23,
  completedPlans: 125
})

// 查询表单
const queryForm = reactive({
  planName: '',
  dispatchType: '',
  status: '',
  createTimeRange: []
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 对话框控制
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const executeDialogVisible = ref(false)
const calendarDialogVisible = ref(false)
const centerDialogVisible = ref(false)

// 表单数据
const currentFormData = ref({})
const currentDetailData = ref({})
const currentExecuteData = ref({})
const isEditMode = ref(false)

// 调度日历数据
const scheduleData = ref([])

// 活跃计划数据
const activePlans = computed(() => {
  return tableData.value.filter(plan => plan.status === 'executing')
})

// 统一模拟数据与筛选分页
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? `0${n}` : `${n}`)
const formatISODateTime = (date: Date) => `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`

const generateMockData = () => {
  const types = ['flood-control', 'water-supply', 'power-generation', 'ecological', 'comprehensive']
  const priorities = ['low', 'medium', 'high', 'urgent']
  const statuses = ['pending', 'executing', 'completed', 'paused', 'cancelled']
  const creators = ['张三', '李四', '王五', '赵六', '孙七']
  const names = ['防洪调度', '供水优化', '发电计划', '生态流量', '综合调度']
  const cnt = randInt(30, 80)
  const data = Array.from({ length: cnt }, (_, i) => {
    const type = randomChoice(types)
    const priority = randomChoice(priorities)
    const status = randomChoice(statuses)
    const name = `${randomChoice(names)}计划_${i + 1}`
    const create = new Date(Date.now() - randInt(0, 60) * 24 * 3600 * 1000)
    const sched = new Date(Date.now() + randInt(-10, 20) * 24 * 3600 * 1000)
    const actual = status === 'pending' ? null : new Date(sched.getTime() + randInt(-120, 60) * 60000)
    return {
      id: Date.now() + i,
      planName: name,
      dispatchType: type,
      priority,
      status,
      scheduledTime: formatISODateTime(sched),
      actualStartTime: actual ? formatISODateTime(actual) : null,
      progress: status === 'completed' ? 100 : status === 'executing' ? randInt(1, 95) : 0,
      creator: randomChoice(creators),
      createTime: formatISODateTime(create),
      description: `关于${name}的说明`
    }
  })
  allData.value = data
}

const applyFiltersAndPaginate = () => {
  const { planName, dispatchType, status, createTimeRange } = queryForm
  let filtered = allData.value.slice()
  if (planName) {
    filtered = filtered.filter(d => d.planName?.includes(planName))
  }
  if (dispatchType) {
    filtered = filtered.filter(d => d.dispatchType === dispatchType)
  }
  if (status) {
    filtered = filtered.filter(d => d.status === status)
  }
  if (createTimeRange && createTimeRange.length === 2) {
    const [start, end] = createTimeRange
    const s = new Date(start).getTime()
    const e = new Date(end).getTime() + 24 * 3600 * 1000 - 1
    filtered = filtered.filter(d => {
      const t = new Date(d.createTime).getTime()
      return t >= s && t <= e
    })
  }
  pagination.total = filtered.length
  const startIdx = (pagination.currentPage - 1) * pagination.pageSize
  const endIdx = startIdx + pagination.pageSize
  tableData.value = filtered.slice(startIdx, endIdx)
}

// 获取调度类型图标
const getDispatchIcon = (type: string) => {
  const iconMap = {
    'flood-control': Umbrella,
    'water-supply': Umbrella,
    'power-generation': Lightning,
    'ecological': Folder,
    'comprehensive': Setting
  }
  return iconMap[type] || Calendar
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood-control': 'danger',
    'water-supply': 'primary',
    'power-generation': 'warning',
    'ecological': 'success',
    'comprehensive': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap = {
    'flood-control': '防洪调度',
    'water-supply': '供水调度',
    'power-generation': '发电调度',
    'ecological': '生态调度',
    'comprehensive': '综合调度'
  }
  return textMap[type] || type
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const typeMap = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'urgent': 'danger'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'urgent': '紧急'
  }
  return textMap[priority] || priority
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    'pending': 'info',
    'executing': 'warning',
    'completed': 'success',
    'paused': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'pending': '待执行',
    'executing': '执行中',
    'completed': '已完成',
    'paused': '已暂停',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 模拟API - 获取调度计划列表
const fetchDispatchPlans = async () => {
  tableLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    if (allData.value.length === 0) {
      generateMockData()
    }
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取调度计划列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页处理
const handlePagination = (page: any) => {
  pagination.currentPage = page.page
  pagination.pageSize = page.limit
  applyFiltersAndPaginate()
}

// 查询
const handleSearch = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    // @ts-ignore
    queryForm[key] = ''
  })
  queryForm.createTimeRange = []
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 显示新增对话框
const showAddDialog = () => {
  currentFormData.value = {}
  isEditMode.value = false
  formDialogVisible.value = true
}

// 编辑计划
const editPlan = (row: any) => {
  currentFormData.value = { ...row }
  isEditMode.value = true
  formDialogVisible.value = true
}

// 查看详情
const viewDetail = (row: any) => {
  currentDetailData.value = row
  detailDialogVisible.value = true
}

// 执行计划
const executePlan = (row: any) => {
  currentExecuteData.value = row
  executeDialogVisible.value = true
}

// 暂停计划
const pausePlan = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认暂停调度计划"${row.planName}"？`, '确认暂停', {
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    row.status = 'paused'
    ElMessage.success('调度计划已暂停')
    
  } catch {
    // 用户取消
  }
}

// 删除计划
const deletePlan = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认删除调度计划"${row.planName}"？`, '确认删除', {
      type: 'warning'
    })
    await new Promise(resolve => setTimeout(resolve, 200))
    const index = allData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      allData.value.splice(index, 1)
      applyFiltersAndPaginate()
    }
    ElMessage.success('调度计划删除成功')
  } catch {
    // 用户取消
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的调度计划')
    return
  }
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个调度计划？`, '确认删除', {
      type: 'warning'
    })
    await new Promise(resolve => setTimeout(resolve, 200))
    const ids = selectedRows.value.map(r => r.id)
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    applyFiltersAndPaginate()
    ElMessage.success('批量删除成功')
  } catch {
    // 用户取消
  }
}

// 批量执行
const handleBatchExecute = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要执行的调度计划')
    return
  }
  
  const executablePlans = selectedRows.value.filter(row => 
    row.status === 'pending' || row.status === 'paused'
  )
  
  if (executablePlans.length === 0) {
    ElMessage.warning('选中的计划中没有可执行的计划')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认执行选中的 ${executablePlans.length} 个调度计划？`, '确认执行', {
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    executablePlans.forEach(row => {
      row.status = 'executing'
      row.actualStartTime = new Date().toISOString()
      row.progress = 0
    })
    
    ElMessage.success('批量执行成功')
    
  } catch {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 显示调度日历
const showScheduleCalendar = () => {
  // 准备日历数据
  scheduleData.value = tableData.value.map(plan => ({
    ...plan,
    date: plan.scheduledTime?.split(' ')[0] || new Date().toISOString().split('T')[0]
  }))
  calendarDialogVisible.value = true
}

// 显示调度中心
const showDispatchCenter = () => {
  centerDialogVisible.value = true
}

// 保存调度计划
const handleSave = async (formData: any) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    if (isEditMode.value) {
      const index = allData.value.findIndex(item => item.id === formData.id)
      if (index > -1) {
        allData.value[index] = { ...formData }
      }
      ElMessage.success('调度计划更新成功')
    } else {
      const newPlan = {
        ...formData,
        id: Date.now(),
        createTime: new Date().toISOString(),
        creator: '当前用户',
        progress: 0
      }
      allData.value.unshift(newPlan)
      ElMessage.success('调度计划创建成功')
    }
    formDialogVisible.value = false
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 执行完成处理
const handleExecutionComplete = (planData: any) => {
  const index = tableData.value.findIndex(item => item.id === planData.id)
  if (index > -1) {
    tableData.value[index] = { ...planData }
  }
  executeDialogVisible.value = false
  ElMessage.success('调度计划执行完成')
}

// 计划控制处理
const handlePlanControl = (action: string, planData: any) => {
  const index = tableData.value.findIndex(item => item.id === planData.id)
  if (index > -1) {
    tableData.value[index] = { ...planData }
  }
  ElMessage.success(`计划${action}成功`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDispatchPlans()
})
</script>

<style scoped>
.dispatch-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  overflow: hidden;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.pending {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.completed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 10px;
}

.table-card {
  border-radius: 8px;
}

.plan-name {
  display: flex;
  align-items: center;
}

.plan-icon {
  margin-right: 8px;
  color: #409eff;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-progress-bar__outer) {
  border-radius: 3px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 3px;
}
</style>